import { useStore } from "@/stores";
import { Friend } from "@/api/ImApi";
import { setChatList, playVoice, handleCall } from "@/static/ts/common";
// 处理个人消息
export async function handlePersonalMessage(data : any) {
	let store = useStore();

	const { Sender, MessageId, Cmd, Content } = data;
	data.chatId = String(Sender);

	try {
		// 获取好友列表
		const friendList = await getFriendList(Sender);
		if (Cmd == 7) {
			let friendInfo = friendList[0];

			let pages = getCurrentPages();
			let currentPage = pages[pages.length - 1];
			if (
				Content.type == "push" &&
				Content.content?.type === "online" &&
				currentPage.route != "pages/rtc/index"
			) {
				handleCall(Content.content.call_type, friendInfo, 0)

			}

			return;
		}

		// 获取最后一条消息
		const lastMessage = await getLastMessage(Sender);
		console.log("获取最后一条消息", lastMessage);
		store.db.loadData("chatList", {
			id: Sender,
		}).then((e : any) => {
			console.log(e, '1111111')
			if (e[0]?.notDisturb != 1) {

				playVoice(3);

			} else {
				console.log('静音了')
			}
		});

		if (
			(lastMessage && lastMessage.MessageId + 1 === MessageId) ||
			MessageId == 1
		) {
			// 消息ID连贯，保存消息到数据库
			await store.db.saveData("singleChat", [
				{ ...data, unread: 1, id: Sender + "_" + MessageId },
			]);
		} else {
			console.log("消息不连贯，不存储", lastMessage?.MessageId, MessageId);
		}
		await setChatList(
			{ ...friendList[0], ...data, id: Sender, Type: 1 },
			Sender
		);
	} catch (error) {
		console.error("Error handling personal message:", error);
	}
}

// 获取好友列表，避免重复请求
export async function getFriendList(userId : string) {
	let store = useStore();
	let friendList = await store.db.loadData("friendList", {
		id: userId,
		sortField: "id",
	});
	if (friendList.length === 0) {
		await Friend(); // 请求远程数据
		friendList = await store.db.loadData("friendList", {
			id: userId,
			sortField: "id",
		});
	}
	return friendList;
}

// 获取单聊消息的最后一条记录
export async function getLastMessage(userId : number) {
	let store = useStore();

	const singleChatList = await store.db.loadData("singleChat", {
		chatId: String(userId),
		Grade: 1,
		page: 1,
		limit: 1,
		Cmd: { $ne: 7 },
	});
	console.log("userId", userId);
	console.log("singleChatList", singleChatList);
	return singleChatList.length > 0 ? singleChatList[0] : null;
}